﻿using System;
using System.Configuration;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using ConvertSourceToHtml.Conversion;

namespace ConvertSourceToHtml.Properties
{
    /// <summary>
    /// Provides methods for accessing CopySourceAsHtml settings.
    /// </summary>
    /// <remarks>
    /// <para>
    /// <see cref="Settings"/> supports XML serialization so that instances can be serialized,
    /// deserialized, and fed into <see cref="Copier"/> for regression testing.
    /// </para>
    /// </remarks>
    public sealed partial class Settings : ICopierSettings, IXmlSerializable
    {
        #region IXmlSerializable Members

        /// <summary>
        /// Does nothing.
        /// </summary>
        /// <returns><see langword="null"/>.</returns>
        public XmlSchema GetSchema()
        {
            return null;
        }

        /// <summary>
        /// Deserializes the settings from an <see cref="XmlReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="XmlReader"/> to deserialize the settings from.</param>
        public void ReadXml(XmlReader reader)
        {
            SettingsProperty property;

            while (reader.Read())
            {
                if (reader.NodeType != XmlNodeType.Element)
                {
                    break;
                }
                property = Properties[reader.Name];
                PropertyValues.Add(new SettingsPropertyValue(property) { PropertyValue = Convert.ChangeType(reader.ReadString(), property.PropertyType) });
            }
            reader.Read();
        }

        /// <summary>
        /// Serializes the settings to an <see cref="XmlReader"/>.
        /// </summary>
        /// <param name="writer">The <see cref="XmlWriter"/> to serialize the settings to.</param>
        public void WriteXml(XmlWriter writer)
        {
            SettingsPropertyValue propertyValue;

            foreach (SettingsProperty property in Properties)
            {
                propertyValue = PropertyValues[property.Name];
                writer.WriteStartElement(property.Name);
                writer.WriteString((string)Convert.ChangeType(propertyValue.PropertyValue, typeof(string)));
                writer.WriteEndElement();
            }
        }

        #endregion
    }
}
